include("util.js");

var karotz_ip="localhost";
//var karotz_ip="192.168.0.15";


var durationName=params[instanceName].duration;
var LEDfunc=params[instanceName].func;
var Color1=params[instanceName].col1;
var Color2=params[instanceName].col2;
var Period=params[instanceName].per;

var duration=0;
if(durationName=="ten") duration=10*1000;
if(durationName=="twenty") duration=20*1000;
if(durationName=="thirty") duration=30*1000;
if(durationName=="one") duration=60*1000;
/*
var duration=10000;
var LEDfunc="light";
var Period=2000;
var Color1="0000FF";
var Color2="00FF9F";
*/
var iteration=Math.floor(duration/Period);
var i=0;

var buttonListener = function(event) {
    if (event == "DOUBLE") {
        exit();
    }
    return true;
}

var cbFunc=function(event) {
	if((event == "CANCELLED") || (event == "TERMINATED")) {
		exit();
   }
}

var pulseFunc=function() {
	log("Begin Pulse");
	karotz.led.light(Color1);
	karotz.led.pulse(Color2,Period,duration,cbFunc);
}

var fadeCb=function(event) {
	if((event == "CANCELLED") || (event == "TERMINATED")) {
		karotz.led.light("000000");
		setTimeout(200,function() {fadeFunc();});
   }
}

var fadeFunc=function() {
	log("Fade : "+i);
	if (i<iteration) {
		i++;
		karotz.led.light(Color1);
		karotz.led.fade(Color2,Period,fadeCb);
	}
	else exit();
}

var light=function(color) {
	log("Light : "+i);
	if (i<iteration) {
		if (color==Color1) {
			karotz.led.light(Color1);
			setTimeout(Period/2,function() {light(Color2);});
		}
		else {
			karotz.led.light(Color2);
			setTimeout(Period/2,function(){light(Color1);});
			i++;
		}
	}
	else {
		exit();
	}
}

var lightFunc=function() {
	log("Begin Light");
	light(Color1);
}

var beginLED=function() {
	log("Begin");
	if (LEDfunc=="pulse") pulseFunc();
	if (LEDfunc=="fade") fadeFunc();
	if (LEDfunc=="light") lightFunc();
}

var onKarotzConnect=function(data) {
    karotz.button.addListener(buttonListener);
	log("Nb iteration : "+iteration);
	beginLED();
}

karotz.connectAndStart(karotz_ip, 9123, onKarotzConnect, {});
